package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentCargoManageBinding;
import com.sgb.kjwl.model.entity.transport.TabEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.adapter.self.logistics.SimpleFragmentAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.CargoManageTabAdapter;
import com.sgb.kjwl.view.ui.fragment.transport.CargoManageItemFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;


/**
 * @author: 杨畔
 * @date: 2020/12/28 10:58
 * @Description: 货源管理
 */
public class CargoManageFragment extends AppLazyFragment {

    FragmentCargoManageBinding binding;
    private final List<Fragment> mFragments = new ArrayList<>();
    private List<TabEntity> mTabs;
    private CargoManageTabAdapter mAdapter;
    private boolean mIsGeneralGoods = true;
    //是否需要刷新全部数据，接收事件后使用
    private boolean mIsNeedRefreshAll = false;

    public static CargoManageFragment newInstance(boolean isGeneralGoods) {
        CargoManageFragment fragment = new CargoManageFragment();
        Bundle args = new Bundle();
        args.putBoolean(RouterKey.BOOLEAN, isGeneralGoods);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_cargo_manage, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (getArguments() != null) {
            mIsGeneralGoods = getArguments().getBoolean(RouterKey.BOOLEAN, true);
        }
        initTab();
        initEvent();
    }

    @Override
    protected void onLazyLoad() {
        initFragment();
    }

    private void initTab() {
        mTabs = new ArrayList<>();
        mTabs.add(new TabEntity("全部"));
        if (mIsGeneralGoods) {
            mTabs.add(new TabEntity("待接单"));
            mTabs.add(new TabEntity("付款中"));
            mTabs.add(new TabEntity("已下架"));
            mTabs.add(new TabEntity("其他"));
        } else {
            mTabs.add(new TabEntity("竞价中", true, 0, 99));
//            mTabs.add(new TabEntity("报价截止"));
            mTabs.add(new TabEntity("其他"));
        }
        mAdapter = new CargoManageTabAdapter(mTabs);
        binding.rvCargoManageTab.setLayoutManager(new GridLayoutManager(getContext(), mIsGeneralGoods ? 5 : 4));
        binding.rvCargoManageTab.setAdapter(mAdapter);
    }

    private void initEvent() {
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mAdapter.setSelectIndex(position);
            binding.vpCargoManage.setCurrentItem(position);
        });
        binding.vpCargoManage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mAdapter.setSelectIndex(position);
            }
        });
    }

    private void initFragment() {
        for (int i = 0; i < mTabs.size(); i++) {
            mFragments.add(CargoManageItemFragment.newInstance(getRequestStateByTabPosition(i), mIsGeneralGoods));
        }
        SimpleFragmentAdapter fragmentAdapter = new SimpleFragmentAdapter(getActivity(), mFragments);
        binding.vpCargoManage.setAdapter(fragmentAdapter);
        binding.vpCargoManage.setOffscreenPageLimit(mIsGeneralGoods ? 4 : 3);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCount(GoodsManageEvent event) {
        //货源管理页面事件
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_CARGO_MANAGE_TAB_COUNT) {
            if ((boolean) event.getObject() == mIsGeneralGoods) {
                updateCount((Integer) event.getMessageData());
            }
        } else if (event.getMessageTag() == EventConstant.UP_AND_DOWN_SUCCESS) {
            refreshAllData();
        }else if (event.getMessageTag() == EventConstant.DELETE_SUCCESS) {
            refreshAllData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void goodsChangeEvent(LogisticsEvent event) {
        //其他页面事件
        switch (event.getMessageTag()) {
            case EventConstant.EVENT_CARGO_RELEASE_SUCCESS:
            case EventConstant.EVENT_GOOD_DETAIL_DELETE:
            case EventConstant.EVENT_GOOD_DETAIL_UP_AND_DOWN_SUCCESS:
            case EventConstant.EVENT_GOODS_AGREED_OFFER:
            case EventConstant.EVENT_REFRESH_OFFER_OWNER_PAGE:
                mIsNeedRefreshAll = true;
                break;
        }
    }

    private void refreshAllData() {
        for (int i = 0; i < mFragments.size(); i++) {
            ((CargoManageItemFragment) mFragments.get(i)).refreshData();
        }
    }

    public void updateCount(int count) {
        if (mAdapter != null && mTabs != null && mTabs.size() > 2) {
            mTabs.get(1).setNumber(count);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取货源对应状态
     */
    private int getRequestStateByTabPosition(int tabPosition) {
        //todo 状态待调整
        //查询状态 0待接单 3付款中 4 报价已截止 5 已下架 6其他
        int state = -1;
        if (mIsGeneralGoods) {
            switch (tabPosition) {
                case 0:
                    state = -1;
                    break;
                case 1:
                    state = 0;
                    break;
                case 2:
                    state = 3;
                    break;
                case 3:
                    state = 5;
                    break;
                case 4:
                    state = 6;
                    break;
            }
        } else {
            switch (tabPosition) {
                case 0:
                    state = -1;
                    break;
                case 1:
                    state = 0;
                    break;
                case 2:
                    state = 6;
                    break;
            }
        }
        return state;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsNeedRefreshAll){
            mIsNeedRefreshAll = false;
            refreshAllData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}